import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:io';
import 'dart:ui' as ui show window;
import 'package:lib_uikit/lib_uikit.dart';

import '../theme/gt_colors_v3.dart';

/// 通用导航栏
class GTAppBar extends StatefulWidget implements PreferredSizeWidget {
  const GTAppBar({
    Key? key,
    this.title,
    this.titleFontSize,
    this.titleStyle,
    this.subTitle,
    this.showDivider = false,
    this.backIcon,
    this.backPrePressed,
    this.backPressed,
    this.rightIcon1,
    this.rightIcon1Pressed,
    this.rightIcon2,
    this.rightIcon2Pressed,
    this.backgroundColor,
    this.brightness,
    this.shouldReserveStatusBarHeight = true,
    this.overlayStyle,
    this.rightIcon1PressedWithContext
  }) : super(key: key);

  final bool showDivider;
  final String? title;
  final double? titleFontSize;
  final TextStyle? titleStyle;
  final String? subTitle;
  final Widget? backIcon;

  final Color? backgroundColor;

  // 点击返回按钮后，前置操作，不会覆盖默认操作
  final VoidCallback? backPrePressed;

  // 点击返回按钮操作，会覆盖默认操作
  final VoidCallback? backPressed;
  final VoidCallback? rightIcon1Pressed;
  final ValueChanged<BuildContext>? rightIcon1PressedWithContext;

  final Widget? rightIcon1;

  final VoidCallback? rightIcon2Pressed;
  final Widget? rightIcon2;

  // 状态栏主题模式
  final Brightness? brightness;

  // 是否预留状态栏高度
  final bool shouldReserveStatusBarHeight;

  final SystemUiOverlayStyle? overlayStyle;

  @override
  State<StatefulWidget> createState() => _GTAppBarState();

  @override
  Size get preferredSize {
    if (Platform.isAndroid) {
      return Size(MediaQueryData.fromWindow(ui.window).size.width, shouldReserveStatusBarHeight ? 44 : 44 - 29);
    } else {
      return Size(MediaQueryData.fromWindow(ui.window).size.width, 44);
    }
  }
}

class _GTAppBarState extends State<GTAppBar> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: widget.overlayStyle ?? GTSystemUiOverlayStyleUtils.getStyleForBackgroundColor(widget.backgroundColor),
      child: _buildAppBar(context),
    );
  }

  Widget _buildAppBar(BuildContext context) {
    return Container(
      color: widget.backgroundColor ?? GTColorsV3.bg1.color,
      padding: EdgeInsets.only(top: widget.shouldReserveStatusBarHeight ? MediaQuery.of(context).padding.top : 0),
      constraints: const BoxConstraints.expand(),
      child: Stack(
        alignment: Alignment.center,
        children: [
          Positioned.directional(
            textDirection: Directionality.of(context),
            start: 0,
            child: GTBackButton(
              backIcon: widget.backIcon,
              onPressed: widget.backPressed ??
                  () {
                    // 先执行前置操作
                    widget.backPrePressed?.call();

                    if (Navigator.of(context).canPop()) {
                      Navigator.of(context).pop();
                    } else {
                      SystemNavigator.pop(animated: true);
                    }
                  },
            ),
          ),
          Container(
            padding: GTEdgeInsetsOnly(left: 48, right: 48),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: [
                Flexible(
                  child: Text(
                    widget.title ?? '',
                    softWrap: true,
                    style: widget.titleStyle ??
                        gtTextStyleW500(fontSize: widget.titleFontSize ?? 18, color: GTColorsV3.text1.color),
                  ),
                ),
                widget.subTitle != null
                    ? Text(
                        widget.subTitle!,
                        style: gtTextStyle(fontSize: 10, color: GTColorsV3.uikitText3V3.color),
                      )
                    : const SizedBox.shrink(),
              ],
            ),
          ),
          Positioned.directional(
            textDirection: Directionality.of(context),
            end: 0,
            child: SizedBox(
              height: 44,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: (widget.rightIcon1 != null || widget.rightIcon2 != null)
                    ? [
                        if (widget.rightIcon2 != null)
                          GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: widget.rightIcon2Pressed,
                            child: widget.rightIcon2,
                          ),
                        if (widget.rightIcon1 != null && widget.rightIcon2 != null) const SizedBox(width: 16),
                        if (widget.rightIcon1 != null) ...[
                          if (widget.rightIcon1PressedWithContext != null) ...[
                            Builder(
                              builder: (BuildContext context) {
                                return GestureDetector(
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    if (widget.rightIcon1PressedWithContext != null) {
                                      widget.rightIcon1PressedWithContext!(context);
                                    }
                                  },
                                  child: widget.rightIcon1!,
                                );
                              },
                            ),
                          ] else ...[
                            GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: widget.rightIcon1Pressed,
                              child: widget.rightIcon1,
                            )
                          ]
                        ]
                      ]
                    : [const SizedBox.shrink()],
              ),
            ),
          ),
          Positioned(
            bottom: 0,
            child: widget.showDivider
                ? Container(
                    color: GTColors.uikitDivider1.color,
                    width: 375,
                    height: 0.5,
                  )
                : const SizedBox.shrink(),
          )
        ],
      ),
    );
  }
}
